using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.JsonWebTokens;
using WebSMS.Core.ResponseEntity;

namespace WebSMS;


[Route("[controller]/[action]")]
[Controller]
public class UserController : ControllerBase
{
    private readonly UserService _userService;
    private readonly UserRuleLinksService _userRulesService;
    private readonly UserPostLinksService _userPostLinksService;

    public UserController(UserService userService, UserRuleLinksService ruleListService,UserPostLinksService userPostLinksService)
    {
        _userService = userService;
        _userRulesService = ruleListService;
        _userPostLinksService = userPostLinksService;
    }

    [HttpPost]
    public async Task<ResponseObject<UserInfo>> Login([FromBody] UserLoginForm userForm)
    {
        UserPo login = await _userService.Login(userForm.UserName, PasswordMd5.md5(userForm.Password));
        if (login is null)
        {
            return new ResponseObject<UserInfo>().Fail("用户名或密码不正确");
        }
        else if (!login.IsActive)
        {
            var rulesByUserId = _userRulesService.GetUserRuleByUserId(login.Id);
            var token = JWTEncryption.Encrypt(new Dictionary<string, object>()
            {
                { "UserId", login.Id }, // 存储Id
                { "Username", login.Username }, // 存储用户名
                { "Email", login.Email }, // 存储邮箱
                { "Phone", login.Phone }, // 存储电话
                { "Rules", rulesByUserId }
            });

            var userInfo = new UserInfo
            {
                Username = login.Username,
                Email = login.Email,
                Phone = login.Phone,
                IsActive = login.IsActive,
                Token = token
            };
            return new ResponseObject<UserInfo>().Ok(userInfo, "登录成功！");
        }
        else
        {
            return new ResponseObject<UserInfo>().Fail("您的账户已被禁用，请联系管理员解封！");
        }
    }

    [HttpGet]
    [Authorize]
    public async Task<ResponseObject<List<UserRuleResponse>>> GetUserList(int page, int size)
    {
        if (page == 0 || size == 0)
        {
            page = 1;
            size = 10;
        }
        var token = HttpContext.Request.Headers["Authorization"].ToString();
        if (token.Equals("") || string.IsNullOrEmpty(token))
        {
            return new ResponseObject<List<UserRuleResponse>>().Fail("身份验证失败,请重新登录!");
        }
        string[] strings = token.Split("  ");
        var jwtToken = JWTEncryption.ReadJwtToken(strings[1]);
        var username = jwtToken.GetClaim("Username").Value;
        var userList = await _userService.GetUserList(username,page, size);
        if (userList.Count == 0)
        {
            return new ResponseObject<List<UserRuleResponse>>().Fail("暂时没有更多的数据！");
        }
        else
        {
            return new ResponseObject<List<UserRuleResponse>>().Ok(userList, "查询成功！");
        }

    }

    [HttpGet]
    [Authorize]
    public async Task<ResponseObject<PagedList<UserPo>>> GetRecoveryUserList(int page, int size)
    {
        var recoveryUser = await _userService.GetRecoveryUserList(page, size);
        return new ResponseObject<PagedList<UserPo>>().Ok(recoveryUser, "查询成功！");
    }

    [HttpPut]
    [Authorize]
    public async Task<ResponseObject<UserPo>> RecoveryUser(Guid id)
    {
      var s = await _userService.RecoveryUser(id);
      return s?new ResponseObject<UserPo>().Ok( "恢复成功！"):new ResponseObject<UserPo>().Fail("该用户不存在！");
    }

    [HttpPut]
    [Authorize]
    public async Task<ResponseObject<UserPo>> BanUser(Guid id)
    {
        var user = await _userService.BannedUserById(id);
        if (user)
        {
            return new ResponseObject<UserPo>().Ok("禁用成功！");
        }
        else
        {
            return new ResponseObject<UserPo>().Fail("该用户不存在！");

        }
    }

    [HttpPut]
    [Authorize]
    public async Task<ResponseObject<bool>> EnableUser(Guid id)
    {
        var user = await _userService.EnableUser(id);
        if (user)
        {
            return new ResponseObject<bool>().Ok("启用成功！");

        }
        else
        {
            return new ResponseObject<bool>().Fail("该用户不存在！");
        }
    }

    [HttpPost]
    [Authorize]
    public async Task<ResponseObject<PagedList<UserPo>>> AddUser([FromBody] UserForm user, int page, int size)
    {
        var id = Guid.NewGuid();
        var userList = await _userService.AddUser(new UserPo
        {
            Username = user.Username,
            Password = PasswordMd5.md5(user.Password),
            Email = user.Email,
            Phone = user.Phone,
            IsActive = false,
            Id = id,
            IsDeleted = false,
            CreateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
            BanDate = "",
            DeleteDate = ""
        }, page, size);
        if (user.Rules.Count != 0)
        {
            foreach (var rule in user.Rules)
            {
              await  _userRulesService.AddUserRule(new UserRuleLinks()
                {
                    Id = Guid.NewGuid(),
                    UserId = id,
                    RuleId = rule
                });
            }
        }
        return new ResponseObject<PagedList<UserPo>>().Ok(userList, "添加成功！");
    }

    [HttpPut]
    [Authorize]
    public async Task<ResponseObject<bool>> UpdateUser([FromBody] UserForm userFrom)
    {
        var user = await _userService.UpdateUser(new UserPo
        {
            Id = userFrom.UserId,
            Username = userFrom.Username,
            Email = userFrom.Email,
            Phone = userFrom.Phone,
            Password = PasswordMd5.md5(userFrom.Password),
            IsActive = userFrom.IsActive,
            IsDeleted = userFrom.IsDeleted,
            CreateDate = userFrom.CreateDate,
            BanDate = userFrom.BanDate,
            DeleteDate = userFrom.DeleteDate
        });
        if (user)
        {
            if (userFrom.Rules.Count != 0)
            {
                foreach (var item in userFrom.Rules)
                {
                   await _userRulesService.AddUserRule(new UserRuleLinks()
                    {
                        Id = Guid.NewGuid(),
                        UserId = userFrom.UserId,
                        RuleId = item
                    });
                }
                
            }
            return new ResponseObject<bool>().Ok(true, "修改成功！");
        }

        return new ResponseObject<bool>().Fail("修改失败！");
    }

    [HttpDelete]
    [Authorize]
    public async Task<ResponseObject<bool>> DeleteUser(Guid id)
    {
        var user = await _userService.DeleteUser(id);
        if (user)
        {
            return new ResponseObject<bool>().Ok(true, "删除成功！");
        }

        return new ResponseObject<bool>().Fail("删除失败！");

    }

    /*********************************************************************************************************************/
    // 查看用户详情
    [HttpGet]
    public async Task<ResponseObject<IQueryable>> GetUserDetail(Guid id)
    {
        var details = await _userService.GetUserDetails(id);
        
        return new ResponseObject<IQueryable>().Ok(details, "获取成功");
    }

    /*********************************************************************************************************************/
    // JWT Token 验证
    [HttpPost]
    public ResponseObject<JsonWebToken> VerifyToken()
    {
        var token = HttpContext.Request.Headers["Authorization"].ToString();
        if (token.Equals("") || string.IsNullOrEmpty(token))
        {
            return new ResponseObject<JsonWebToken>().Fail("身份验证失败,请重新登录!");
        }

        string[] strings = token.Split("  ");
        var valueTuple = JWTEncryption.Validate(strings[1]);
        if (valueTuple.Item1)
        {
            return new ResponseObject<JsonWebToken>().Ok(valueTuple.Token, "验证成功");
        }

        return new ResponseObject<JsonWebToken>().Fail("身份验证失败,请重新登录!");
    }

    [HttpPost]
    [Authorize]
    public async Task<ResponseObject<Object>> VerifyUserPassword([FromBody] UserLoginForm userLoginForm)

    {
        var token = HttpContext.Request.Headers["Authorization"].ToString();
        if (token.Equals("") || string.IsNullOrEmpty(token))
        {
            return new ResponseObject<Object>().Fail("身份验证失败,请重新登录!");
        }

        string[] strings = token.Split("  ");
        var valueTuple = JWTEncryption.Validate(strings[1]);
        if (valueTuple.Item1)
        {
            var task = await _userService.VerifyUserPassword(userLoginForm.UserName, userLoginForm.Password);
            if (task)
            {
                return new ResponseObject<Object>().Ok("验证成功");
            }
        }

        return new ResponseObject<Object>().Fail("身份验证失败,请检查你的密码!");
    }

    /*********************************************************************************************************************/
    // 用户规则
    [HttpPost]
    [Authorize]
    public ResponseObject<IQueryable> GetUserAndRuleList()
    {
        IQueryable list = _userRulesService.GetUserAndRuleList();

        return new ResponseObject<IQueryable>().Ok(list, "获取成功");
    }

    [HttpPost]
    [Authorize]
    public async Task<ResponseObject<IQueryable>> AddUserRule([FromBody] UserRuleForm userRuleForm)
    {
        if (userRuleForm.RuleList.Count == 0)
        {
            return new ResponseObject<IQueryable>().Fail("请至少添加一个规则!");
        }
        else
        {
            foreach (var item in userRuleForm.RuleList)
            {
                await _userRulesService.AddUserRule(new UserRuleLinks()
                    { Id = Guid.NewGuid(), UserId = userRuleForm.UserId, RuleId = item });
            }

            return new ResponseObject<IQueryable>().Ok("添加成功");
        }
    }

    [HttpDelete]
    [Authorize]
    public async Task<ResponseObject<IQueryable>> DeleteUserRule(Guid userId, Guid ruleId)
    {
        await _userRulesService.DeleteUserRule(userId, ruleId);
        return new ResponseObject<IQueryable>().Ok("删除成功");
    }
    
    /*********************************************************************************************************************/
    // 用户菜单权限
    [HttpGet]
    [Authorize]
    public async Task<ResponseObject<IQueryable>> GetUserMenuList()
    {
        var userMenuList = await _userService.GetUserMenuList();
        return new ResponseObject<IQueryable>().Ok(userMenuList,"获取成功");
    }

    [HttpPost]
    [Authorize]
    public async Task<ResponseObject<IQueryable>> AddUserMenu([FromBody] UserMenuForm userMenuForm)
    {
         Guid userId = userMenuForm.UserId;
         if (userMenuForm.MenuId.Count != 0)
         {
             foreach (var item in userMenuForm.MenuId)
             {
                 await _userService.AddUserMenu(userId,item);
             }
         }
         return new ResponseObject<IQueryable>().Ok("添加成功");
    }

    [HttpDelete]
    [Authorize]
    public async Task<ResponseObject<bool>> DeleteUserMenu(Guid userId)
    {
        var s = await _userService.DeleteUserMenu(userId);
        if (s)
        {
            return new ResponseObject<bool>().Ok("删除成功");
        }
        return new ResponseObject<bool>().Fail("删除失败");
    }
    
    /*********************************************************************************************************************/
    //用户岗位
    [HttpPost]
    [Authorize]
    public async Task<ResponseObject<IQueryable>> AddUserPost([FromBody] UserPostForm userPostForm)
    {
      await _userPostLinksService.AddUserToPost(userPostForm.UserId, userPostForm.PostsId);
      return new ResponseObject<IQueryable>().Ok("添加成功");   
    }
}